//
//  CHCrashHandler.swift
//  CHSimpleUI
//
//  Created by cyptt on 2022/12/8.
//

import UIKit
public typealias Completion = ()->Void;
public typealias CrashCallback = (String,Completion)->Void;
public var crashCallBack: CrashCallback?

func signalHandler(signal:Int32) -> Void {
    let stackTrace = Thread.callStackSymbols.joined(separator: "\r\n")
    crashCallBack?(stackTrace,{
        unregisterSignalHandler();
        exit(signal);
    });
}
func registerSignalHanlder()
{
    objc_setUncaughtExceptionHandler { (_response:Any?) in
        if let signal = _response as? Int32 {
            signalHandler(signal: signal)
        }
        else if let exception = _response as? NSException {
            //            print("++++++++++++++++++ 异常信息 ++++++++++++++++++")
            //            NSLog("name:%@",exception.name.rawValue)
            //            NSLog("reason:%@",exception.reason ?? "--")
            //            NSLog("userInfo:%@",exception.userInfo ?? [:])
            //            NSLog("Stack Trace:%@",exception.callStackSymbols)
            //            NSLog("Stack ReturnAddresses:\n%@", exception.callStackReturnAddresses)
            //            NSLog("Exception All:\n%@", exception)
            crashCallBack?(exception.reason ?? exception.callStackSymbols.joined(separator: "\r\n"),{
                unregisterSignalHandler();
                exception.raise()
            });
        }
    }
    
    signal(SIGINT,  signalHandler);
    signal(SIGSEGV, signalHandler);//野指针，僵尸对象
    signal(SIGTRAP, signalHandler);
    signal(SIGABRT, signalHandler);
    signal(SIGILL,  signalHandler);
    signal(SIGBUS,  signalHandler);
    signal(SIGFPE,  signalHandler);
    signal(SIGTERM, signalHandler);
    signal(SIGKILL, signalHandler);//CPU无法执行的代码(比如无效指令、除以0等)
    signal(SIGPIPE, signalHandler);
}



func unregisterSignalHandler()
{
    signal(SIGINT,  SIG_DFL);
    signal(SIGSEGV, SIG_DFL);
    signal(SIGTRAP, SIG_DFL);
    signal(SIGABRT, SIG_DFL);
    signal(SIGILL,  SIG_DFL);
    signal(SIGBUS,  SIG_DFL);
    signal(SIGFPE,  SIG_DFL);
    signal(SIGTERM, SIG_DFL);
    signal(SIGKILL, SIG_DFL);
    signal(SIGPIPE, SIG_DFL);
}


class CHCrashHandler: NSObject {


 
    public static func setup(callBack:@escaping CrashCallback){
        crashCallBack = callBack;
        registerSignalHanlder();
    }
}
